<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="命令标题" prop="cmdTitle">
        <el-input v-model="formData.cmdTitle" placeholder="请输入命令标题" />
      </el-form-item>
      <el-form-item label="关键词" prop="keyword">
        <el-input v-model="formData.keyword" placeholder="请输入关键词, 多个使用英文逗号分隔" />
      </el-form-item>
      <el-form-item label="传感器类型" prop="sensorType">
        <el-select v-model="formData.sensorType" placeholder="请选择传感器类型">
          <el-option :label="option.label" :value="option.value" v-for="option in getDictOptions('lm_sensor_type')" :key="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" prop="operateType">
        <el-select v-model="formData.operateType" placeholder="请选择操作类型">
          <el-option :label="option.label" :value="option.value" v-for="option in getDictOptions('lm_operation_type')" :key="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-input-number v-model="formData.priority" placeholder="请输入优先级" />
      </el-form-item>
      <el-form-item label="操作幅度" prop="step">
        <el-input v-model="formData.step" placeholder="请输入操作幅度" />
      </el-form-item>
      <el-form-item label="是否可用" prop="enable">
        <el-select
          v-model="formData.enable"
          placeholder="请选择是否可用"
          clearable
          class="!w-240px"
        >
          <el-option :label="option.label" :value="option.value" v-for="option in getDictOptions('infra_boolean_string')" :key="option.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="扩展" prop="extension">
        <el-input type="textarea" v-model="formData.extension" placeholder="请输入扩展" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { AudioCommandApi, AudioCommandVO } from '@/api/resource/audiocommand'
import {getDictOptions} from "@/utils/dict";

/** 语音指令配置 表单 */
defineOptions({ name: 'AudioCommandForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  cmdTitle: undefined,
  keyword: undefined,
  sensorType: undefined,
  operateType: undefined,
  step: undefined,
  enable: undefined,
  priority: undefined,
  remark: undefined,
  extension: undefined,
})
const formRules = reactive({
  cmdTitle: [{ required: true, message: '命令标题不能为空', trigger: 'blur' }],
  keyword: [{ required: true, message: '关键词, 多个使用英文逗号分隔不能为空', trigger: 'blur' }],
  sensorType: [{ required: true, message: '传感器类型不能为空', trigger: 'change' }],
  operateType: [{ required: true, message: '操作类型不能为空', trigger: 'change' }],
  enable: [{ required: true, message: '是否可见不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let data = await AudioCommandApi.getAudioCommand(id);
      data.enable += "";
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  let extension = formData.value.extension;
  if(extension) {
    try {
      extension = JSON.parse(extension);
    } catch (e) {
      message.error('扩展参数格式错误，该字段要求为json字符串');
    }
    if(typeof extension !== 'object') {
      return;
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data:any = {
      ...formData.value as unknown as AudioCommandVO
    }
    if(data.enable === "true" || data.enable) {
      data.enable = true;
    } else {
      data.enable = false;
    }
    if (formType.value === 'create') {
      await AudioCommandApi.createAudioCommand(data)
      message.success(t('common.createSuccess'))
    } else {
      await AudioCommandApi.updateAudioCommand(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    cmdTitle: undefined,
    keyword: undefined,
    sensorType: undefined,
    operateType: undefined,
    step: undefined,
    enable: undefined,
    extension: undefined,
    priority: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
